function get(ApiManager, body, success, failure) {
  ApiManager.sendRequest('get', body, success, failure);
}

function post(ApiManager, body, success, failure) {
  ApiManager.sendRequest('post', body, success, failure);
}

angular.module('liemallfodder')
  .factory('ApiManager', function ($rootScope, $http, $location, Toast) {
    var BASE_URL = $rootScope.BASE_URL;
    var apiManager = {};

    apiManager.sendRequest = function (method, body, success, failure) {
      var url = BASE_URL + body.name;
      if (method === 'post') {
        apiManager.post(url, body.data, success, failure);
      } else {
        apiManager.get(url, body.data, success, failure);
      }

      printRequestBody(body, method);
    };

    function printRequestBody(body, method) {
      console.log('\n-------------http request-----------------\n');
      console.log('url:' + BASE_URL + body.name);
      console.log('method:' + method);
      console.log('parameters:' + JSON.stringify(body.data, null, "\t"));
    }

    apiManager.get = function (url, body, success, failure) {
      $http.get(url, {params: body})
        .then(function (response) {
            if (response) {
              success(response.data);
              console.log(response.data);
              console.log('-------------------end----------------------\n\n');
            } else {
              failure('data is null');
            }
          },
          function (error) {
            failure(error);
          });
    };

    apiManager.post = function (url, body, success, failure) {
      $http.post(url, body)
        .then(function (response) {
            if (response) {
              success(response.data);
            } else {
              failure('data is null');
            }
          },
          function (error) {
            failure(error);
          });
    };

    apiManager.hasError = function (result) {
      if (result && result.code == 0) {
        return false;
      }

      console.log(result);
      if (!result) {
        Toast.show('data is null');
        return true;
      }

      Toast.show(result ? result.message : '未知错误');
      return true;
    };

    apiManager.showError = function (error) {
      if (!error) {
        Toast.show('服务器返回为空');
        return;
      }

      if ((typeof error) === 'string') {
        Toast.show(error);
      }

      if (error.status) {
        switch (error.status) {
          case -1: {
            Toast.show('服务器无响应');
            break;
          }
          case 500: {
            Toast.show('服务器内部错误');
            break;
          }
        }

        return;
      }

      Toast.show(error);
    };

    return apiManager;
  });
